package top.crossrun.webview.bridge.webview.x5;

import android.view.ViewGroup;
import android.view.ViewParent;

import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;

import top.crossrun.webview.bridge.core.pls.BridgeCallBackFunction;
import top.crossrun.webview.bridge.core.pls.BridgeJSEval;

/**
 * create by Run
 * on 2020/8/24 17:48
 * do
 */
public class X5JSEval implements BridgeJSEval {
    private WebView webView;

    public X5JSEval(WebView webView) {
        this.webView = webView;
    }

    @Override
    public void evaluateJavascript(String script, final BridgeCallBackFunction callback) {
        webView.evaluateJavascript(script, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if (callback != null) {
                    if (value != null && value.startsWith("\"")
                            && value.endsWith("\"")) {
                        value = value.substring(1, value.length() - 1)
                                .replaceAll("\\\\", "");
                    }
                    callback.onCallBackFunction(value);
                }
            }
        });
    }

    @Override
    public void loadUrl(String url) {
        webView.loadUrl(url);
    }

    @Override
    public void onDestory() {
        if (webView != null) {
            webView.loadUrl("about:blank");
            webView.getSettings().setBuiltInZoomControls(false);
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;    这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.removeAllViews();
            try {
                webView.destroy();
            } catch (Throwable ex) {

            }
            webView = null;
        }
    }
}
